package com.java.al.string;

public class MemoryTest {
	public void string() {
		String s = "abcdefghijklmnop";
		System.out.print("当前虚拟机最大可用内存为:");
		System.out.println(Runtime.getRuntime().maxMemory() / 1024 / 1024 + "M");
		System.out.print("循环前，虚拟机已占用内存:");
		System.out.println(Runtime.getRuntime().totalMemory() / 1024 / 1024 + "M");
		int count = 0;
		while (true) {
			try {
				s += s;
				count++;
			} catch (Error o) {
				System.out.println("循环次数:" + count);
				System.out.println("String实际字节数:" + s.length() / 1024 / 1024 + "M");
				System.out.print("循环后，已占用内存:");
				System.out.println(Runtime.getRuntime().totalMemory() / 1024 / 1024 + "M");
				System.out.println("Catch到的错误:" + o);
				break;
			}
		}
	}

	public void stringBuffer() {
		StringBuffer s = new StringBuffer("abcdefghijklmnop");
		System.out.print("当前虚拟机最大可用内存为:");
		System.out.println(Runtime.getRuntime().maxMemory() / 1024 / 1024 + "M");
		System.out.print("循环前，虚拟机已占用内存:");
		System.out.println(Runtime.getRuntime().totalMemory() / 1024 / 1024 + "M");
		int count = 0;
		while (true) {
			try {
				s.append(s);
				count++;
			} catch (Error o) {
				System.out.println("循环次数:" + count);
				System.out.println("String实际字节数:" + s.length() / 1024 / 1024 + "M");
				System.out.print("循环后，已占用内存:");
				System.out.println(Runtime.getRuntime().totalMemory() / 1024 / 1024 + "M");
				System.out.println("Catch到的错误:" + o);
				break;
			}
		}
	}

	public static void main(String args[]) {
		MemoryTest mt = new MemoryTest();
		mt.string();
		System.out.println("--------------------可恶的分割线--------------------");
		mt.stringBuffer();
	}
}
